<?php
namespace jy_carfee;
defined('BY_JYA') or exit('error');
/*
	销售员奖励计算
	
*/
class commission extends \plugin{
	/*
		生成奖励
	*/
	function create($order){
		$this->order=$order;		
		$this->commission_order=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$this->order['mid'],
			'ordersn'=>$this->order['ordersn'],
			'order_price'=>$this->order['price'],
			'commission_money'=>0,
			'guan_money'=>0,
			'fuwu_money'=>0,
			'createtime'=>TIMESTAMP,
		);
		//1、默认方式: 除运费和会员折扣(或促销折扣)外其他所有费用全部计算奖励；实际支付方式: 只计算实际支付和余额抵扣部分的奖励(包括余额支付)
		if($this->setting['commissiontype']==2){
			$this->commission_order['commission_price']=$this->order['price'];
		}else{
			$this->commission_order['commission_price']=$this->order['price']-$this->order['dispatchprice'];
		}
		$myteam=$this->get('team',array('mid'=>$this->order['mid'],'uniacid'=>$_SESSION['uniacid']));
		if($myteam['id']){
			$fromuser=$myteam['fromuser'];
		}else{
			$member=$this->get('member',array('mid'=>$this->order['mid']),array('id','mid','fromuser'));
			if(!$member['id'] || !$member['fromuser']){
			    if(!$member['id']){
                    $member['mid']=$this->order['mid'];
                }
				$member=$this->model('member')->register($member);
			}
			$fromuser=$member['fromuser'];
		}
		//自购送车指标
		foreach($this->order['goods'] as $goods){
			$ignore=$this->get('goods',array('goods_id'=>$goods['goodsid'],'uniacid'=>$_SESSION['uniacid']));
			if(intval($ignore['cheb']) || intval($ignore['kuanb'])){
				$this->update('member',array('cheb +='=>intval($ignore['cheb']),'kuanb +='=>intval($ignore['kuanb'])),array('uniacid'=>$_SESSION['uniacid'],'mid'=>$this->order['mid']));
				$post=array(
					'mid'=>$this->order['mid'],
					'fee'=>intval($ignore['cheb']),
					'status'=>1,
				);
				if($post['fee']>0){
					$this->model('model')->addcheblog($post,1,'自购送车指标');
				}
				if($myteam['id'] && $post['fee']>0){
					$this->model('member')->update_agent_level($myteam['mid'],true,$post['fee']);
				}
				$post['fee']=intval($ignore['kuanb']);
				if($post['fee']>0){
					$this->model('model')->addkuanblog($post,1,'自购送车款标');
				}
			}
		}
		$this->commission_order['teamid']=$fromuser;	
		if($myteam['level_id']){
			$this->nowlevel=$this->getcolumn('level',array('id'=>$myteam['level_id']),'level');
		}else{
			$this->nowlevel=0;
		}
		$parameter=array(
			'params'=>array('uniacid'=>$_SESSION['uniacid']),
			'orderby'=>'level asc',
			'limit'=>'1',
		);		
		$levels=$this->get_list('level',$parameter);
		$minlevel=$levels[0]['level'];
		$parameter['orderby']='level desc';
		$levels=$this->get_list('level',$parameter);
		$this->commission_order['maxlevel']=$maxlevel=$levels[0]['level'];
		$levelnum=12;	
		$this->isfuwu=0;
		//极差奖励单线等级ABCDE，第一级没有奖励，低于自己的没有奖励，平级没有奖励
		for($i=0;$i<$levelnum;$i++){
				if(!$fromuser){
					break;
				}
				$team=$this->get('team',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']));
				$fromuser=$this->getcolumn('member',array('mid'=>$fromuser,'uniacid'=>$_SESSION['uniacid']),'fromuser');
				$level=$this->getcolumn('level',array('id'=>$team['level_id']),'level');
				$level=$level?:0;
				if($level==$this->nowlevel){
					$isping=1;
				}
				$this->create_redcommission($team,$i,$isping);
				//当等级匹配时，奖励
				$this->nowlevel=$level;
				//如果他的上级是我
				$ta_agent_id=$this->getcolumn('member',array('mid'=>$fromuser),'fromuser');
				if($ta_agent_id==$team['mid']){
					break;
				}
		}
		//生成分销订单
		if($this->commission_order['isarea']){
			$indata=$this->commission_order;
			unset($indata['isarea']);
			unset($indata['maxlevel']);
			unset($indata['guan_money']);
			unset($indata['fuwu_money']);
			$this->insert('order',$indata);
		}
		return true;
	}
	/*
		奖励发放;
	*/
	function create_redcommission($agent,$key_level='',$isping=0){
			$commission_level=$agent['level_id'];
			if(!$agent['level_id']){
				//获取默认等级奖励比例
				$level=$this->plugin_setting('default_level');
				$level_id=0;
			}else{
				$level=$this->get('level',array('id'=>$agent['level_id'],'uniacid'=>$_SESSION['uniacid']));
				$level['setdata']=json_decode($level['setdata'],true);
				$level_id=$level['id'];
			}
			$sale_per=$level['sale_per'];
			$guan_per=$level['guan_per'];
			$fuwu_per=$level['fuwu_per'];
			$ping_per=$level['ping_per'];
			$sale_money=0;
			$guan_money=0;
			$fuwu_money=0;
			$ping_money=0;
			$order_price=$this->commission_order['commission_price'];
			$remark=array(
				'level_id'=>$level_id,
				'order_price'=>$order_price,
				'goods_commission'=>array(),
			);			
			//先检查是否存在商品独立奖励规则，如果存在则对订单相应商品部分金额单独计算奖励
			$this->needorder=false;
			foreach($this->order['goods'] as $goods){
				$ignore=$this->get('goods',array('goods_id'=>$goods['goodsid'],'uniacid'=>$_SESSION['uniacid']));
				$post=array(
					'mid'=>$agent['mid'],
					'fee'=>intval($ignore['gongb']),
					'status'=>1,
				);
				if($post['fee']>0 && !$key_level){
					$this->update('member',array('gongb +='=>intval($post['fee'])),array('uniacid'=>$_SESSION['uniacid'],'mid'=>$agent['mid']));
					$this->model('model')->addgongblog($post,1,'直推送月供标');
				}
				if(!$ignore['id']){
					$this->needorder=true;
					continue;
				}
				if($ignore['ignore']){
					$goods_commission=array();
					$order_price=$order_price-$goods['total_price'];
					continue;
				}else{
					$goods_commission=$ignore['commissions']?json_decode($ignore['commissions'],true):array();
				}
				$order_price=$order_price-$goods['total_price'];
				foreach($goods_commission as $gc){
						if(!$gc['level_id']){
							$goods_sale_per=$gc['sale_per'];
							$goods_guan_per=$gc['guan_per'];
							$goods_fuwu_per=$gc['fuwu_per'];
							$goods_ping_per=$gc['ping_per'];
						}
						if($gc['level_id']!=$level_id){
							continue;
						}else{
							$goods_sale_per=$gc['sale_per'];
							$goods_guan_per=$gc['guan_per'];
							$goods_fuwu_per=$gc['fuwu_per'];
							$goods_ping_per=$gc['ping_per'];
							break;
						}
				}
				//销售奖励
				if(substr($goods_sale_per,-1)=='%'){
					$goods_sale_money=intval($goods['total_price']*substr($goods_sale_per,0,-1))/100;
					$sale_money+=$goods_sale_money;
				}else{
					$goods_sale_money=intval($goods_sale_per*$goods['total']*100)/100;
					$sale_money+=$goods_sale_money;
				}
				//管理奖极差
				if(substr($goods_guan_per,-1)=='%'){
					$goods_guan_money=intval($goods['total_price']*substr($goods_guan_per,0,-1))/100;
					$guan_money+=$goods_guan_money;
				}else{
					$goods_guan_money=intval($goods_guan_per*$goods['total']*100)/100;
					$guan_money+=$goods_guan_money;
				}
				//服务费
				if(substr($goods_fuwu_per,-1)=='%'){
					$goods_fuwu_money=intval($goods['total_price']*substr($goods_fuwu_per,0,-1))/100;
					$fuwu_money+=$goods_fuwu_money;
				}else{
					$goods_fuwu_money=intval($goods_fuwu_per*$goods['total']*100)/100;
					$fuwu_money+=$goods_fuwu_money;
				}
				//平级奖金
				if($isping){
					if(substr($goods_ping_per,-1)=='%'){
						$goods_ping_money=intval($goods['total_price']*substr($goods_ping_per,0,-1))/100;
						$ping_money +=$goods_ping_money;
					}else{
						$goods_ping_money=intval($goods_ping_per*$goods['total']*100)/100;
						$ping_money +=$goods_ping_money;
					}
				}
				$remark['goods_commission'][]=array('goods_id'=>$goods['goodsid'],'total_price'=>$goods['total_price'],'total'=>$goods['total'],'commission_per'=>$goods_sale_per,'commission_money'=>$goods_sale_money);
			}
			if($order_price>0 && $this->needorder){
				//销售奖励
				if(substr($sale_per,-1)=='%'){
					$goods_sale_money=intval($goods['total_price']*substr($sale_per,0,-1))/100;
					$sale_money+=$goods_sale_money;
				}else{
					$goods_sale_money=intval($sale_per*$goods['total']*100)/100;
					$sale_money+=$goods_sale_money;
				}
				//管理奖极差
				if(substr($guan_per,-1)=='%'){
					$goods_guan_money=intval($goods['total_price']*substr($guan_per,0,-1))/100;
					$guan_money+=$goods_guan_money;
				}else{
					$goods_guan_money=intval($guan_per*$goods['total']*100)/100;
					$guan_money+=$goods_guan_money;
				}
				//服务费
				if(substr($fuwu_per,-1)=='%'){
					$goods_fuwu_money=intval($goods['total_price']*substr($fuwu_per,0,-1))/100;
					$fuwu_money+=$goods_fuwu_money;
				}else{
					$goods_fuwu_money=intval($fuwu_per*$goods['total']*100)/100;
					$fuwu_money+=$goods_fuwu_money;
				}
				//平级奖金
				if($isping){
					if(substr($ping_per,-1)=='%'){
						$goods_ping_money=intval($goods['total_price']*substr($ping_per,0,-1))/100;
						$ping_money +=$goods_ping_money;
					}else{
						$goods_ping_money=intval($ping_per*$goods['total']*100)/100;
						$ping_money +=$goods_ping_money;
					}
				}
			}
			$remark['commission_money']=$money;
			if($sale_money>0 && !$key_level){
				$this->commission_order['commission_money']+=$sale_money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>$level_id,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$sale_money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
					'type'=>0,
				);
				$this->insert('commission',$new_commission);
			}
			if($guan_money>0 && $guan_money>$this->commission_order['guan_money']){
				$lastfee=$guan_money-$this->commission_order['guan_money'];
				$this->commission_order['commission_money']+=$lastfee;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>$level_id,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$lastfee,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
					'type'=>1,
				);
				$this->insert('commission',$new_commission);
			}
			if($fuwu_money>0 && $level_id>$this->nowlevel && !$this->isfuwu){
				$this->commission_order['commission_money']+=$fuwu_money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>$level_id,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$fuwu_money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
					'type'=>2,
				);
				$this->insert('commission',$new_commission);
				$this->isfuwu=1;
			}
			if($ping_money>0 && $isping){
				$this->commission_order['commission_money']+=$ping_money;
				$new_commission=array(
					'uniacid'=>$_SESSION['uniacid'],
					'mid'=>$agent['mid'],
					'agent_id'=>$agent['id'],
					'area_code'=>$agent['area_code'],
					'level'=>$level_id,
					'ordersn'=>$this->order['ordersn'],
					'money'=>$ping_money,
					'remark'=>ijson_encode($remark),
					'createtime'=>TIMESTAMP,
					'status'=>$this->setting['is_jiesuan']?:0,
					'type'=>3,
				);
				$this->insert('commission',$new_commission);
			}
			//判断是否存在销售员
			$this->commission_order['isarea']=true;
			//此处判断分销商是否满足升级条件，如果满足则升级分销商等级
			$agent_update=array(
				'order_price +='=>$this->commission_order['order_price'],
				'order_num +='=>1,
				'commission_money +='=>$money,
			);
			$this->update('team',$agent_update,array('id'=>$agent['id']));
			$this->model('member')->update_agent_level($agent['mid']);
	}
	/*
		订单完成时，把奖励状态由初始的订单待完成升级为待结算
	*/
	public function order_complete($order){
		$this->update('commission',array('status'=>1,'complete_time'=>TIMESTAMP),array('ordersn'=>$order['ordersn'],'status'=>0));
	}
	/*
		创建结算单
	*/
	public function create_balance($mid,$post=array()){
		$type=intval($post['type']);
		if(!$mid){
			exi('请先选择要结算的会员！','error');
		}
		if($post['pay_type']=='alipay'){
			if(!$post['realname']){
				exi('请先填写真实姓名！','error');
			}
			if(!$post['alipay']){
				exi('请先填写支付宝帐号！','error');
			}
			if(!$post['alipay1']){
				exi('请确认帐号','error');
			}
			if($post['alipay1']!=$post['alipay']){
				exi('确认帐号与支付宝帐号不匹配！','error');
			}
		}
		if($post['pay_type']=='union'){
			if(!$post['realname']){
				exi('请输入姓名','error');
			}
			if(!$post['bankname']){
				exi('请输入所属银行','error');
			}
			if(!$post['bankcard']){
				exi('请银行卡号','error');
			}
			if(!$post['bankcard1']){
				exi('请确认卡号','error');
			}
			if($post['bankcard']!=$post['bankcard1']){
				exi('确认卡号与银行卡号不匹配！','error');
			}
		}
		//获取可结算奖励
		$params=array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1);
		if($this->setting['balance_day']){
			//结算天数
			$time=TIMESTAMP-intval($this->setting['balance_day'])*86400;
			$params['complete_time <']=$time;
		}
		if($type){
			$params['type']=$type;
			$isgetfee=$this->model('member')->check_isgetfee($mid,$type);
			if($isgetfee){
				exi('您已结算过了该奖金！不能再结算！','error');
			}
		}else{
			$params['type <=']=3;
		}
		$commissions=$this->getall('commission',$params);
		if(!$commissions){
			exi('没有可结算的奖励！','error');
		}
		$commission_num=count($commissions);
		$money=0;
		$jifen=0;
		foreach($commissions as $commission){
			$money+=$commission['money'];
			$jifen+=$commission['jifen'];
		}
		//结算最低奖励检测
		if($money<$this->setting['balance_fee']){
			exi('满￥'.$this->setting['balance_fee'].'才可结算！','error');
		}
		if($type==5){
			if($this->setting['jie_credit']!=1){
				$post['pay_type']='credit';
			}else{
				$post['pay_type']='jifen';
			}
		}
		$new_balance=array(
			'uniacid'=>$_SESSION['uniacid'],
			'mid'=>$mid,
			'balancesn'=>get_ordersn($this->tablename('commission'),'balancesn','AC'),
			'commission_num'=>$commission_num,
			'money'=>$money,
			'jifen'=>$jifen,
			'pay_type'=>$post['pay_type'],
			'realname'=>$post['realname'],
			'alipay'=>$post['alipay'],
			'bankname'=>$post['bankname'],
			'bankcard'=>$post['bankcard'],
			'createtime'=>TIMESTAMP,
			'fee_type'=>$type,
			'status'=>0,
		);
		//结算手续费
		if($this->setting['balance_per']){
			$new_balance['balance_pay']=intval($new_balance['money']*$this->setting['balance_per'])/100;
		}else{
			$new_balance['balance_pay']=0;
		}
		$new_balance['final_money']=$new_balance['money']-$new_balance['balance_pay'];
		$this->insert('balance',$new_balance);
		$balance_id=pdo_insertid();
		foreach($commissions as $commission){
			$update=array(
				'status'=>2,
				'balancesn'=>$new_balance['balancesn'],
			);
			$this->update('commission',$update,array('id'=>$commission['id']));
		}
		return $balance_id;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'check_time'=>TIMESTAMP,
			'remark'=>$remark,
		);
		$this->update('balance',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type){
		$balance=$this->get('balance',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn']);
		$update=array(
			'status'=>3,
			'pay_type'=>$pay_type,
			'pay_trade_no'=>$trade_no,
			'pay_time'=>TIMESTAMP,
		);
		$this->update('balance',$update,array('id'=>$balance['id']));
		if($balance['jifen']>0){
			cfc('core')->member_credit($balance['mid'],'credit1',$balance['jifen'],true,$this->plugin_name,$remark='佣金转积分');
		}
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销奖励打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn){
		$params=array(
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'remark'=>'代理商奖励发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return '';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return '';
		exi('暂不支持打款到银行账户！','error');
	}

	public function commission_remark($remark){
		if(!$remark){
			return '';
		}
		$remark=json_decode($remark,true);
		$goods_str='';
		if($remark['goods_commission']){
			foreach($remark['goods_commission'] as $goods){
				$goods['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$goods['goods_id']),'title');
				$goods_str.="商品ID【{$goods['goods_id']}】，商品名称【{$goods['title']}】，商品数量【{$goods['total']}】，商品总价【{$goods['total_price']}】，奖励规则【{$goods['commission_per']}】，分销奖励【{$goods['commission_money']}】\n";
			}
		}else{
			$goods_str='';
		}
		$remark['level_title']=pdo_getcolumn('jy_carfee_level',array('uniacid'=>$_SESSION['uniacid'],'level'=>$remark['level_id']),'title');
		$remark['level_title']=$remark['level_title']?:'默认等级';
		$remark_str=<<<TPL
团长等级ID【{$remark['level_id']}】，等级名称【{$remark['level_title']}】，奖励等级【{$remark['commission_level']}】，订单总价【{$remark['order_price']}】
商品独立奖励：
{$goods_str}
订单奖励：
除去设置独立奖励的商品外订单金额【{$remark['order_commission']['order_price']}】，奖励规则【{$remark['order_commission']['commission_per']}%】，分销奖励【{$remark['order_commission']['commission_money']}】
奖励总计：【{$remark['commission_money']}】
TPL;
		return $remark_str;
	}
}